package test.linkedlistsplitter;

public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    public static void main(String[] args) {
        ListNode root = null, last = null;
        for (int i = 0; i < 0; i++) {
            ListNode node = new ListNode(i + 1);
            if (i == 0) {
                root = node;
                last = node;
            } else {
                last.next = node;
                last = last.next;
            }
        }
        ListNode[] listNodes = new ListNode(0).new Solution().splitListToParts(root, 3);
        System.out.println(listNodes);
    }

    class Solution {
        public ListNode[] splitListToParts(ListNode root, int k) {

            int n = 0;
            ListNode cur = root;
            while (cur != null) {
                cur = cur.next;
                n++;
            }
            ListNode[] nodes = new ListNode[k];
            cur = root;
            ListNode prev;

            int smallSize = n / k;//小链表的大小
            int bigNum = n % k;//大链表的个数


            for (int i = 0; i < k; i++) {
                nodes[i] = cur;
                for (int j = 0; j < smallSize - (i < bigNum ? 0 : 1); j++) {
                    //大链表
                    cur = cur.next;
                }

                if (cur != null) {
                    prev = cur;
                    cur = cur.next;
                    prev.next = null;//尾节点后置节点置空
                }
            }

            return nodes;
        }
    }
}
